package com.spider.silence.pool;

import com.google.common.collect.Lists;
import com.spider.silence.downloader.AiKaForumDownLoader;
import com.spider.silence.downloader.ZuiChengduDownLoader;
import com.spider.silence.utils.PropertiesUtil;
import org.apache.log4j.Logger;

import java.util.LinkedList;

/**
 * @author 夏茂轩
 * @package com.spider.silence.pool
 * @Date 2017/3/8 20:16
 */
public class AiKaDownLoaderPool {
    private Logger logger = Logger.getLogger(ZuiChengduDownLoaderPool.class);
    private static  AiKaDownLoaderPool instance=new AiKaDownLoaderPool();
    protected LinkedList<AiKaForumDownLoader> pool = Lists.newLinkedList();
    private AiKaDownLoaderPool(){
        int initNum= Integer.parseInt(PropertiesUtil.getVal("AiKa.DownLoader.Pool.initNum"));
        for(int i=0;i<initNum;i++){
            AiKaForumDownLoader downLoader =new AiKaForumDownLoader();
            synchronized (pool){
                pool.add(downLoader);
                pool.notifyAll();
            }
        }
    }

    public  static AiKaDownLoaderPool getInstance(){
        return  instance;
    }

    public  void releaseDownLoader(AiKaForumDownLoader downloader) {
        if (downloader != null) {
            synchronized (pool) {
                pool.addLast(downloader);
                pool.notifyAll();
            }
        }
    }

    public  AiKaForumDownLoader fetchDownLoader(long mills) throws InterruptedException {
        synchronized (pool){
            if(mills<=0){
                while (pool.isEmpty()){
                    pool.wait();
                }
                return pool.removeFirst();
            }else {
                long future= System.currentTimeMillis()+mills;
                long remianing=mills;
                while (pool.isEmpty() && remianing >0){
                    pool.wait(remianing);
                    remianing=future-System.currentTimeMillis();
                }
                AiKaForumDownLoader downLoader =null;
                if(!pool.isEmpty()){
                    downLoader=pool.removeFirst();
                }
                return downLoader;
            }
        }
    }
    public void empty(){
        pool=Lists.newLinkedList();
    }
}
